package com.kyub.spring.gears.namespace;

import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.util.StringUtils;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;

import java.util.Iterator;
import java.util.List;

public class ListFiledsParserDelegate {


    public void parse(Element pojoElement, AbstractBeanDefinition pojoBeanDefinition) {
        final List listFileds = DomUtils.getChildElementsByTagName(pojoElement, "listFields");
        System.out.println("listFileds " + listFileds + " " + listFileds.size());
        if (listFileds.size() > 0) {

            Iterator<Element> listFiledIterator = DomUtils.getChildElementsByTagName((Element) listFileds.get(0), "listField").iterator();
            ManagedList listFiledsList = new ManagedList(listFileds.size());
            while (listFiledIterator.hasNext()) {
                final Element fieldElement = listFiledIterator.next();
                listFiledsList.add(fieldElement.getAttribute("name"));

            }
            listFiledIterator = DomUtils.getChildElementsByTagName((Element) listFileds.get(0), "fieldLayout").iterator();
            while (listFiledIterator.hasNext()) {
                final Element fieldElement = listFiledIterator.next();
                RootBeanDefinition layoutFiled = new RootBeanDefinition(com.kyub.spring.gears.model.FieldLayoutMetadata.class);

                layoutFiled.getPropertyValues().addPropertyValue("refPropertyName", fieldElement.getAttribute("name"));
                layoutFiled.getPropertyValues().addPropertyValue("label", fieldElement.getAttribute("label"));
                if (StringUtils.hasText(fieldElement.getAttribute("hrefPattern"))) {
                    layoutFiled.getPropertyValues().addPropertyValue("hrefPattern", fieldElement.getAttribute("hrefPattern"));
                    layoutFiled.getPropertyValues().addPropertyValue("hrefParams", fieldElement.getAttribute("hrefParams"));
                }
                if (StringUtils.hasText(fieldElement.getAttribute("formatter"))) {
                    layoutFiled.getPropertyValues().addPropertyValue("formatter", fieldElement.getAttribute("formatter"));
                }
                listFiledsList.add(layoutFiled);

            }

            pojoBeanDefinition.getPropertyValues().addPropertyValue(new PropertyValue("listFields", listFiledsList));

        }
    }
}
